package com.gougou.rpc.custom;

import com.gougou.rpc.custom.utils.RpcDecoder;
import com.gougou.rpc.custom.utils.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 框架的RPC客户端，用于发送RPC请求
 * Created by EX-ZHANZHENQIANG001 on 2018-05-02.
 */
public class RpcClient extends SimpleChannelInboundHandler<RpcResponse>{

    private static final Logger LOGGER = LoggerFactory.getLogger(RpcClient.class);

    private String host;

    private int port;

    private RpcResponse response;

    //对象锁，用于进行并发同步控制
    private Object obj = new Object();

    public RpcClient(String host, int port) {
        this.host = host;
        this.port = port;
    }


    /**
     * 读取服务器端返回的结果
     * @param channelHandlerContext
     * @param rpcResponse
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse) throws Exception {
        this.response = rpcResponse;
        synchronized (obj) {
            //唤醒所有在此对象上等待锁的线程
            obj.notifyAll();
        }
    }


    /**
     * 链接服务端，发送消息
     * @param request
     * @return
     */
    public RpcResponse send(RpcRequest request) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //创建启动类对象
            Bootstrap bootstrap = new Bootstrap();
            //设置启动参数
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //获取管道，添加阀门
                            socketChannel.pipeline()
                                    .addLast(new RpcEncoder(RpcRequest.class))
                                    .addLast(new RpcDecoder(RpcResponse.class))
                                    .addLast(RpcClient.this);
                        }
                    }).option(ChannelOption.SO_KEEPALIVE, true);
            //链接服务器
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //将request对象写入outbundle处理后发出（即RpcEncoder编码器）
            channelFuture.channel().writeAndFlush(request).sync();

            //用线程等待的方式决定是否需要关闭连接
            //其意义是：先在此阻塞，等待获取到服务器端的返回后，被唤醒，从而关闭网络连接
            synchronized (obj) {
                //在obj对象上等待资源锁
                obj.wait();
            }
            //处理返回结果
            if(response != null) {
                //关闭网络连接
                channelFuture.channel().closeFuture().sync();
                }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //始终关闭,资源组group
            group.shutdownGracefully();
        }
    }


    /**
     * 重新异常处理方法
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error("client caught exception", cause);
        ctx.close();
    }
}
